// import { createApp } from 'vue'
// import './style.css'
// import App from './App.vue'
//
// import router from './router';
// import ElementPlus from 'element-plus'
// import 'element-plus/dist/index.css'
//
// const app = createApp(App);
//
// app.use(router).use(ElementPlus);
//
// app.mount('#app')
import { createApp } from 'vue'
import App from './App.vue'
import {routes} from './router'
import ElementPlus from "element-plus";
import 'element-plus/dist/index.css'
import {createRouter, createWebHistory, RouteRecordRaw, RouterHistory} from 'vue-router'
import { renderWithQiankun, qiankunWindow } from 'vite-plugin-qiankun/dist/helper'

let router: any = null
let instance: any = null
let history: RouterHistory

declare global {
    interface Window {
        __POWERED_BY_QIANKUN__: any
        __INJECTED_PUBLIC_PATH_BY_QIANKUN__: any
    }
}
const modules = import.meta.glob('./views/**/*.vue');
function render(props: any = {}) {
    const { container,microRouters } = props
    console.log(props)
    instance = createApp(App)

    // 将props挂载到全局上，用于主子应用的交互
    instance.config.globalProperties.$sonProps = props

    history =createWebHistory ( '/')

    // 注册ElementPlus
    instance.use(ElementPlus);

    // 注册路由
    router = createRouter({
        history,
        routes
    })
    if(microRouters&&microRouters.length){
        setRouter(microRouters,router)
    }
    instance.use(router)

    instance.mount(container ? container.querySelector("#app") : "#app");

    if (qiankunWindow.__POWERED_BY_QIANKUN__) {
        console.log('我正在作为子应用运行。。。')
    }
}
function setRouter(microRouters: RouteRecordRaw[],router:any){
    microRouters.forEach(async (route) => {
        if (route.meta?.microViewPath && typeof route.meta?.microViewPath == 'string') {
            route.component = modules['./views' + route.meta?.microViewPath + '.vue'];
        }
       await router.addRoute(route);
    });
}
renderWithQiankun({
    mount(props: any) {
        render(props);
    },
    bootstrap() {
    },
    update() {
    },
    unmount() {
        instance.unmount();
        instance._container.innerHTML = "";
        instance = null;
        history.destroy() // 不卸载router会导致其他应用路由失败
        router = null
    }
});

if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
    render({})
}
